from typing import List, Dict, Any, Optional
from com.linkstec.utils.db_utils import DatabasePool
import mysql.connector


class BaseDao:
    def __init__(self, connection=None):
        self.connection = connection

    def _execute(self, query: str, params: tuple = None, fetch: bool = False):
        cursor = None
        conn = self.connection or DatabasePool.get_instance().get_connection()

        try:
            cursor = conn.cursor(dictionary=True)
            cursor.execute(query, params or ())

            if fetch:
                result = cursor.fetchall()
            else:
                result = cursor.rowcount
                if not self.connection:  # 非事务操作自动提交
                    conn.commit()

            return result
        except mysql.connector.Error as err:
            logger.error(f"Database error: {err}")
            raise
        finally:
            if cursor: cursor.close()
            if not self.connection and conn.is_connected():
                conn.close()

    def execute_query(self, query: str, params: tuple = None) -> List[Dict[str, Any]]:
        return self._execute(query, params, fetch=True)

    def execute_update(self, query: str, params: tuple = None) -> int:
        return self._execute(query, params, fetch=False)